package com.jic.member.controller.manage;

import com.jic.common.utils.IDUtils;
import com.jic.member.exception.AppRuntimeException;
import com.jic.member.api.rest.MemberDistributorApi;
import com.jic.member.entity.DisCommissionInfo;
import com.jic.member.request.CommissionInfoResquest;
import com.jic.member.service.DisCommissionInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@ResponseBody
@RequestMapping("/distributor")
@Slf4j
public class DistributorController implements MemberDistributorApi {


    @Autowired
    private DisCommissionInfoService disCommissionInfoService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveCommission(CommissionInfoResquest request) {
        log.info("开始进入佣金保存==========》》" + request.toString());
        try {
            DisCommissionInfo disCommissionInfo = new DisCommissionInfo();
            disCommissionInfo.setOrderNo(request.getOrderNo());
            List<DisCommissionInfo> disCommissionInfoList = disCommissionInfoService.query(disCommissionInfo);

            //修改状态
            if (CollectionUtils.isNotEmpty(disCommissionInfoList)) {
                DisCommissionInfo disCommissionInfo1 = new DisCommissionInfo();
                disCommissionInfo1.setId(disCommissionInfoList.get(0).getId());
                disCommissionInfo1.setStatus(request.getStatus());
                disCommissionInfoService.update(disCommissionInfo1);


            } else {
                //保存
                DisCommissionInfo disCommissionInfo1 = new DisCommissionInfo();
                disCommissionInfo1.setStatus(1);
                disCommissionInfo1.setCommissionNo(IDUtils.GenerateBillNo("C"));
                disCommissionInfo1.setMemberId(request.getThirdUserId());
                disCommissionInfo1.setCreateTime(new Date());
                disCommissionInfo1.setSettleAccounts(request.getSettleAccounts());
                disCommissionInfo1.setOrderNo(request.getOrderNo());
                disCommissionInfoService.insert(disCommissionInfo1);
            }

            return Boolean.TRUE;
        } catch (Exception e) {
            log.error("9999", e);
            throw new AppRuntimeException("9999", "佣金明细保存失败");
        }
    }
}
